package com.joysuch.wwyt.api.mh.socket;

import com.alibaba.fastjson.JSON;
import com.joysuch.wwyt.api.mh.enums.MonitPointSendType;
import com.joysuch.wwyt.api.mh.service.MonitPointConfigService;
import com.joysuch.wwyt.api.mh.socket.dto.MhMonitPointWsDataDetailDto;
import com.joysuch.wwyt.api.mh.socket.dto.MhMonitPointWsDataDto;
import com.joysuch.wwyt.api.sync.SyncConstants;
import com.joysuch.wwyt.core.entity.BaseConfig;
import com.joysuch.wwyt.core.service.BaseConfigService;
import com.joysuch.wwyt.mh.storage.MonitorPointData;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
@Component
public class MhMonitPointSocketSender {

    private static final String COMP_ID_TAIXIANG = "320671004";

    private static final String DATE_FORMAT_COLLECT_TIME = "yyyy-MM-dd HH:mm:ss";

    @Autowired
    private MonitPointConfigService monitPointConfigService;
    @Autowired
    private BaseConfigService baseConfigService;
    private static final DateFormat simpleDateFormat = new SimpleDateFormat(DATE_FORMAT_COLLECT_TIME);

    public void sendMessage(List<MonitorPointData> list) {
        log.info("sendMessage start size {}", list.size());
        //每次最多发送20条
        int maxSize = 20;
        int count = 0;
        if (list == null) {
            log.debug("... mh socket sender: monitor point list is null, no data to send out.");
            return;
        }
        RMap<String, String> configMap = monitPointConfigService.getMointPointConfigMap(MonitPointSendType.SOCKET.getCode());
        MhMonitPointWsDataDto msgDto = new MhMonitPointWsDataDto();
        msgDto.setCorpId(COMP_ID_TAIXIANG);
        msgDto.setCollectTime(simpleDateFormat.format(new Date()));
        List<MhMonitPointWsDataDetailDto> detailList = new ArrayList<>();
        String config[] = null;
        for (MonitorPointData data : list) {
            MhMonitPointWsDataDetailDto detailDto = new MhMonitPointWsDataDetailDto();
            config = configMap.get(data.getPointCode()).split(",");
            //监测点Code包含则发送， 否则忽略
            if (configMap.containsKey(data.getPointCode())) {
                detailDto.setPointId(config[0]);
                detailDto.setPointValue(data.getValue() * Double.valueOf(config[1]));
                detailList.add(detailDto);
            }
        }
        // 把数据列表分隔成 20 条一组发送
        int totalCount = detailList.size();
        if (totalCount < 20) {
            //数量少于20 直接发送
            msgDto.setDataList(detailList);
            sendMessageOut(msgDto);
            return;
        }
        // 数据大于20条
        int cnt = 0;
        List<MhMonitPointWsDataDetailDto> subList = new ArrayList<>(20);
        for (MhMonitPointWsDataDetailDto d : detailList) {
            cnt++;
            subList.add(d);
            if (cnt == 20) {
                msgDto.setDataList(subList);
                sendMessageOut(msgDto);
                subList.clear();
                cnt = 0;
            }
        }
        if (cnt > 0) {
            msgDto.setDataList(subList);
            sendMessageOut(msgDto);
        }


    }

    /**
     * 3.数据发送示例：
     *
     * @param msgDto
     * @@{"corpId":"320101001001","collectTime":"2020-03-11 10:27:00","dataList":[{"pointId":"320101001001001","pointValue":"11.4"},{"pointId":"320101001001002","pointValue":"12.4"}]}$$
     * （注：需要在json字符串前加@@作为开始符，结尾加$$作为结束符。如果需要上传点位比较多最好分多个包上传，一个包建议传20个数据点的数据）
     * 4.	数据响应格式
     * 示例：{"success":"true","time":"2020-03-11 10:27:00","message":"上传成功
     */
    private void sendMessageOut(MhMonitPointWsDataDto msgDto) {
        StringBuffer message = new StringBuffer("@@").append(JSON.toJSONString(msgDto)).append("$$");
        log.debug("... mh socket sender: sendMessageOut call  ..." + message);

         BaseConfig sendOpen = baseConfigService.getBaseConfigFromRedis(SyncConstants.MH_MONITPOINT_API_SOCKET_OPEN);
         if(sendOpen == null || "false".equalsIgnoreCase(sendOpen.getValue())){
             return ;
         }
        String sendIp = baseConfigService.getBaseConfigFromRedis(SyncConstants.MH_MONITPOINT_API_SOCKET_IP).getValue();
        String sendPort = baseConfigService.getBaseConfigFromRedis(SyncConstants.MH_MONITPOINT_API_SOCKET_PORT).getValue();
        MhWebSocketClientInstance.getWebSocketClientAndSend(message.toString(), sendOpen.getValue(), sendIp, Integer.parseInt(sendPort));
        log.debug("websocket sendout message: " + message.toString());
    }

}
